package com.king.nio.filechannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ByteBuffer 文件读取案例
 *
 * @author king
 * @date 2020/12/26 22:53
 */
public class NioFileChannel02 {
    public static void main(String[] args) throws IOException {
        // 创建文件的输入流
        File file = new File("e:/NioFileChannel01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        // 通过 fileInputStream 获取对应的 FileChannel -> 实际类型FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        // 将通道的数据写入 Buffer
        fileChannel.read(byteBuffer);

        // 将 byteBuffer 的直接数据 转成字符串
        System.out.println(new String(byteBuffer.array()));

        // 关闭流
        fileInputStream.close();
    }
}
